package org.skydiveapp;

import java.util.List;

import org.skydiveapplibrary.data.Signature;
import org.skydiveapplibrary.repository.SignatureRepository;
import org.skydiveapplibrary.ui.DrawingView;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

public class SignatureActivity extends Activity
{
	// repositories
	private SignatureRepository repository = new SignatureRepository(this);
	
	// menus
	private MenuItem saveMenu;
	private MenuItem clearMenu;
	
	@Override 
    public void onCreate(Bundle savedInstanceState)
    { 
    	super.onCreate(savedInstanceState);
    	
    	setContentView(R.layout.signature_view);
    	
    	// init header
    	TextView headerText = (TextView)findViewById(R.id.FormHeaderTextView);
    	headerText.setText(R.string.signature_header_label);
    	
    	// setup autocomplete license field
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, repository.getSignatureLicenses());
        AutoCompleteTextView signatureLicenseField = (AutoCompleteTextView) findViewById(R.id.SignatureLicenseField);
        signatureLicenseField.setAdapter(adapter);
    }
	
	private void clear()
	{
		DrawingView drawingView = (DrawingView)findViewById(R.id.SignatureDrawingView);
		drawingView.clear();
	}
	
	private void save()
	{
		// get ui components
		DrawingView drawingView = (DrawingView) findViewById(R.id.SignatureDrawingView);
		TextView licenseField = (TextView) findViewById(R.id.SignatureLicenseField);

		// get signature data
		byte[] data = drawingView.getImageData();
		String license = licenseField.getText().toString();

		// get log entry ids
		List<Integer> logEntryIds = getIntent().getIntegerArrayListExtra(
				Constants.EXTRA_SELECTED_LOG_ENTRY_IDS);

		// create signature
		Signature signature = new Signature();
		signature.setImage(data);
		signature.setLicense(license);

		// save signature
		SignatureRepository repository = new SignatureRepository(this);
		repository.addSignature(signature, logEntryIds);
		
		// finish
		finish();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		clearMenu = menu.add(R.string.log_entry_diagram_clear);
		clearMenu.setIcon(R.drawable.ic_menu_clear);
		
		saveMenu = menu.add(R.string.done_button);
		saveMenu.setIcon(R.drawable.ic_menu_save);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item == saveMenu)
		{
			save();
        	return true;
		}
		else if (item == clearMenu)
		{
			clear();
        	return true;
		}
		else
		{
			return super.onOptionsItemSelected(item);
		}
	}
}
